/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.knolle.lotes.gui;

import java.awt.event.ActionEvent;
import java.io.File;
import java.util.List;
import javax.swing.AbstractAction;
import org.marcelo.agro.core.DynamicLookup;
import org.marcelo.agro.core.EntitiesJXTable;
import org.marcelo.comun.file.FilesHelper;
import org.marcelo.agro.entidades.Lotes;
import org.marcelo.agro.core.PopupMenuListener;
import org.marcelo.agro.core.api.ILotes;
import org.marcelo.agro.entidades.eventos.LotesEvent;
import org.marcelo.agro.lotes.presenter.LotesPresenter;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.util.Lookup;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import org.marcelo.agro.lotes.util.LotesTableModel;
import org.marcelo.comun.habilidades.CSVExporter;
import org.marcelo.comun.habilidades.CSVImporter;
import org.marcelo.comun.habilidades.Reload;
import org.marcelo.comun.notificaciones.Notificaciones;
import org.openide.NotifyDescriptor;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.Utilities;
import org.openide.util.lookup.AbstractLookup;
import org.openide.util.lookup.InstanceContent;


/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//org.knolle.lotes.gui//ListaLotes//EN",
autostore = false)
@TopComponent.Description(preferredID = "ListaLotesTopComponent",
//iconBase="SET/PATH/TO/ICON/HERE", 
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
@ActionID(category = "Window", id = "org.knolle.lotes.gui.ListaLotesTopComponent")
@ActionReference(path = "Menu/Ver" /*
 * , position = 333
 */)
@TopComponent.OpenActionRegistration(displayName = "#CTL_ListaLotesAction",
preferredID = "ListaLotesTopComponent")
@Messages({
    "CTL_ListaLotesAction=Lotes",
    "CTL_ListaLotesTopComponent=Ventana de lotes",
    "HINT_ListaLotesTopComponent=Esta es la lista de lotes"
})
public final class ListaLotesTopComponent extends TopComponent implements LookupListener {
    
    Lookup.Result result;
    ILotes il = Lookup.getDefault().lookup(ILotes.class);
    PopupMenuListener popUpListener;
    LotesPresenter presenter;
    
    InstanceContent content = new InstanceContent();
    
    Lookup habilidades = new AbstractLookup(content);
    
//    private AbstractAction accionEditar;
//    private AbstractAction accionNuevo;
    private AbstractAction accionRecargar;
//    private AbstractAction accionBorrar;
    private LotesTableModel lotesTableModel = new LotesTableModel();
    
    private String txtTotalSuperficie;
    private String txtTotalSuperficieAlquilada;
    private String txtTotalSuperficiePropia;
    
    private void iniciarAcciones(){
//        accionNuevo = new AbstractAction() {
//            @Override
//            public void actionPerformed(ActionEvent ae){
//            }
//        };
//        accionEditar = new AbstractAction() {
//            @Override
//            public void actionPerformed(ActionEvent e) {
//                throw new UnsupportedOperationException("Not supported yet.");
//            }
//        };
        accionRecargar = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent ae){
                recargarDatos();
            }
        };
//        accionBorrar= new AbstractAction() {
//            @Override
//            public void actionPerformed(ActionEvent ae){
//            }
//        };
    }
    
    public ListaLotesTopComponent() {
        iniciarAcciones();
        initComponents();
        setName(Bundle.CTL_ListaLotesTopComponent());
        setToolTipText(Bundle.HINT_ListaLotesTopComponent());
        
        getActionMap().put("RefreshAction",accionRecargar);
        
        javax.swing.SwingWorker<List<Lotes>,Lotes> worker = new javax.swing.SwingWorker<List<Lotes>, Lotes>(){
            

            
            @Override
            protected List<Lotes> doInBackground() throws Exception {
                //Crear una instancia de la interfaz
//                ILotes il = Lookup.getDefault().lookup(ILotes.class);
                return  il.getAll();
                
            }

            @Override
            protected void done() {
                try {
                    lotesTableModel.getList().clear();
                    lotesTableModel.getList().addAll(get());
                    lotesTableModel.fireTableDataChanged();
                }
                catch (Exception e){}
            }
            
            
            
        };
        worker.execute();
        associateLookup(habilidades);
        content.add(importer);
        content.add(reload);
        content.add(exporter);
//        Iniciar el presenter
        presenter = new LotesPresenter();
        initTextLabels();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        popupMenuTabla = new javax.swing.JPopupMenu();
        menuNuevo = new javax.swing.JMenuItem();
        menuEditar = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        menuBorrar = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JPopupMenu.Separator();
        menuRecargar = new javax.swing.JMenuItem();
        jScrollPane1 = new javax.swing.JScrollPane();
        TablaLotes = new EntitiesJXTable();
        jSeparator3 = new javax.swing.JSeparator();
        lblTotalSuperficie = new javax.swing.JLabel();
        lblTotalSuperficiePropia = new javax.swing.JLabel();
        lblTotalSuperficieAlquilada = new javax.swing.JLabel();

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        menuNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/knolle/lotes/gui/blue_plus_24x24.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(menuNuevo, org.openide.util.NbBundle.getMessage(ListaLotesTopComponent.class, "ListaLotesTopComponent.menuNuevo.text")); // NOI18N
        menuNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuNuevoActionPerformed(evt);
            }
        });
        popupMenuTabla.add(menuNuevo);

        menuEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/knolle/lotes/gui/Edit_24x24.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(menuEditar, org.openide.util.NbBundle.getMessage(ListaLotesTopComponent.class, "ListaLotesTopComponent.menuEditar.text")); // NOI18N
        menuEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuEditarActionPerformed(evt);
            }
        });
        popupMenuTabla.add(menuEditar);
        popupMenuTabla.add(jSeparator1);

        menuBorrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/knolle/lotes/gui/Trash.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(menuBorrar, org.openide.util.NbBundle.getMessage(ListaLotesTopComponent.class, "ListaLotesTopComponent.menuBorrar.text")); // NOI18N
        menuBorrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuBorrarActionPerformed(evt);
            }
        });
        popupMenuTabla.add(menuBorrar);
        popupMenuTabla.add(jSeparator2);

        menuRecargar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/knolle/lotes/gui/Refresh.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(menuRecargar, org.openide.util.NbBundle.getMessage(ListaLotesTopComponent.class, "ListaLotesTopComponent.menuRecargar.text")); // NOI18N
        menuRecargar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuRecargarActionPerformed(evt);
            }
        });
        popupMenuTabla.add(menuRecargar);

        TablaLotes.setModel(lotesTableModel);
        jScrollPane1.setViewportView(TablaLotes);

        org.openide.awt.Mnemonics.setLocalizedText(lblTotalSuperficie, org.openide.util.NbBundle.getMessage(ListaLotesTopComponent.class, "ListaLotesTopComponent.lblTotalSuperficie.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(lblTotalSuperficiePropia, org.openide.util.NbBundle.getMessage(ListaLotesTopComponent.class, "ListaLotesTopComponent.lblTotalSuperficiePropia.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(lblTotalSuperficieAlquilada, org.openide.util.NbBundle.getMessage(ListaLotesTopComponent.class, "ListaLotesTopComponent.lblTotalSuperficieAlquilada.text")); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addComponent(jSeparator3)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblTotalSuperficie)
                        .addGap(18, 18, 18)
                        .addComponent(lblTotalSuperficiePropia)
                        .addGap(18, 18, 18)
                        .addComponent(lblTotalSuperficieAlquilada)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblTotalSuperficie)
                    .addComponent(lblTotalSuperficiePropia)
                    .addComponent(lblTotalSuperficieAlquilada))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void menuRecargarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuRecargarActionPerformed
        // TODO add your handling code here:
        recargarDatos();
    }//GEN-LAST:event_menuRecargarActionPerformed

    private void menuBorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuBorrarActionPerformed
        // TODO add your handling code here:
//        obtener la fila, luego borrar la fila
//        JPopupMenu popUp = popupMenuTabla
//        mostrar un mensaje con la fila a borrar
        int row = TablaLotes.getSelectedRow();
        int rowModel = TablaLotes.convertRowIndexToModel(row);
        Lotes lote = lotesTableModel.getList().get(rowModel);
       
        if (Notificaciones.showMessageBox(Notificaciones.QUESTION_MESSAGE, "En realidad desea borrar?") == NotifyDescriptor.YES_OPTION ) {
           //Intentar Borrar Elemento
           try { 
               il.delete(lote);    
           }
           catch (Exception ex){
               Notificaciones.showMessageBox(Notificaciones.ERROR_MESSAGE, "No se pudo eliminar el elemento por: "+ex.getMessage());
           }
           finally {
               recargarDatos();
           }
        }
    }//GEN-LAST:event_menuBorrarActionPerformed

    private void menuEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuEditarActionPerformed
        int row = TablaLotes.getSelectedRow();
        int rowModel = TablaLotes.convertRowIndexToModel(row);
        
        Lotes lote = (Lotes) lotesTableModel.getList().get(rowModel);
//        Lanzar el editor del Objeto
//        new LotesWizardAction(lote);
        EditarLote edit = new EditarLote(lote);
        edit.show() ;
        recargarDatos();
//        if (edit.show() == EditarLote.MODIFICADO) {
//            recargarDatos();
//        }
        //Recargar datos
    }//GEN-LAST:event_menuEditarActionPerformed

    private void menuNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuNuevoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_menuNuevoActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private org.jdesktop.swingx.JXTable TablaLotes;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JPopupMenu.Separator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JLabel lblTotalSuperficie;
    private javax.swing.JLabel lblTotalSuperficieAlquilada;
    private javax.swing.JLabel lblTotalSuperficiePropia;
    private javax.swing.JMenuItem menuBorrar;
    private javax.swing.JMenuItem menuEditar;
    private javax.swing.JMenuItem menuNuevo;
    private javax.swing.JMenuItem menuRecargar;
    private javax.swing.JPopupMenu popupMenuTabla;
    // End of variables declaration//GEN-END:variables
    @Override
    public void componentOpened() {
        popUpListener = new PopupMenuListener(popupMenuTabla,TablaLotes);
        TablaLotes.addMouseListener(popUpListener);
//        TablaLotes.setComponentPopupMenu(popupMenuTabla);
        
        result = Utilities.actionsGlobalContext().lookupResult(Lotes.class);
        result.addLookupListener(this);
        // TODO add custom code on component opening
//        Mostrar el Status bar
       actualizarTotales();
       
        
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
        TablaLotes.removeMouseListener(popUpListener);
        result.removeLookupListener(this);
        
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    @Override
    public void resultChanged(LookupEvent le) {
        //Implementar el cambio del los datos en el modelo de la tabla
        recargarDatos();
        
    }
    
    private void recargarDatos(){
        
        lotesTableModel.getList().clear();
        try{
            lotesTableModel.getList().addAll(il.getAll());
        }
        catch(Exception e) {
            Notificaciones.notificar("Error con la base de datos", e.toString());
             System.err.println(e.getStackTrace());
        }
        lotesTableModel.fireTableDataChanged();
        actualizarTotales();
        
    }
    
    private CSVImporter importer = new CSVImporter() {
            @Override
            public void csvToLocalData() {
                //Abrir la ventana para seleccionar el archivo
                File file = FilesHelper.showOpenDilogForCSV();
                //Chequear el archivo
                if (file !=null && file.exists()) {
                    try {
                        if (il.saveCSVtoLote(file)){
                            recargarDatos();
//                            Lanzar el evento para los interezados
                            LotesEvent ev = new LotesEvent(LotesEvent.TIPOS_EVENTO.CREATED);
                            DynamicLookup.getDefault().add(ev);
                            DynamicLookup.getDefault().remove(ev);
                        }
                    }
                    catch (Exception e) {
                     //Mostrar un error con el mensaje de error
                        Notificaciones.showMessageBox(Notificaciones.ERROR_MESSAGE, "No se importo por: "+e.getMessage());
                    }
                }
               
            }
    };
    
    private Reload reload = new Reload() {

        @Override
        public void reload() {
            recargarDatos();
        }
    };
    
    private CSVExporter exporter = new CSVExporter() {

        @Override
        public void exportToCSV() {
            try {
                File file = FilesHelper.showOpenDilogForCSV();
                il.saveLoteToCsv(file);
                //Mostrar las notificaciones
                Notificaciones.notificar("Exportado con exito!!!", "los datos fueron exportados satisfactoriamente");
            }
            catch(Exception e) {
                Notificaciones.showMessageBox(Notificaciones.ERROR_MESSAGE, "No se exportp por: "+e.toString());
            }
        }
    };
    
//    private Object showNotification(int tipo,String mensaje) {
//        int tipoMensaje;
//        switch (tipo) {
//            case 0: tipoMensaje = NotifyDescriptor.ERROR_MESSAGE;
//                break;
//            case 1: tipoMensaje = NotifyDescriptor.INFORMATION_MESSAGE;
//                break;
//            case 2: tipoMensaje = NotifyDescriptor.WARNING_MESSAGE;
//                break;
//            case 3: tipoMensaje = NotifyDescriptor.YES_NO_OPTION;
//                break;
//            default: tipoMensaje = NotifyDescriptor.DEFAULT_OPTION;
//         }
//        NotifyDescriptor nd = new NotifyDescriptor.Message(mensaje ,tipoMensaje );
//        return DialogDisplayer.getDefault().notify(nd);
//    
//    }

    private void initTextLabels() {
        txtTotalSuperficie = lblTotalSuperficie.getText();
        txtTotalSuperficieAlquilada = lblTotalSuperficieAlquilada.getText();
        txtTotalSuperficiePropia = lblTotalSuperficiePropia.getText();
        
    }
    
    private void actualizarTotales(){
        lblTotalSuperficie.setText(txtTotalSuperficie + presenter.getTotalSuperficie());
        lblTotalSuperficieAlquilada.setText(txtTotalSuperficieAlquilada + presenter.getTotalSuperficieAlquilada());
        lblTotalSuperficiePropia.setText(txtTotalSuperficiePropia + presenter.getTotalSuperficiePropia());
                
    }
    
}
